﻿using System.IO;
using Xceed.Compression;
using Xceed.FileSystem;
using Xceed.Zip;

namespace picomp
{
    internal class ZipWriter
    {
        private ZipArchive _archive;

        public ZipWriter(string filename)
        {
            Filename = filename.Trim();
        }

        public string Filename { get; private set; }

        private void CreateZipFile()
        {
            if (_archive == null)
            {
                if (File.Exists(Filename)) File.Delete(Filename);

                _archive = new ZipArchive(new DiskFile(Filename))
                           {
                               DefaultCompressionLevel = CompressionLevel.None,
                               DefaultCompressionMethod = CompressionMethod.Stored,
                               DefaultFolderPersistence = FolderPersistence.NotPersisted
                           };
                _archive.BeginUpdate();
            }
        }

        public void Close()
        {
            _archive.EndUpdate();
        }

        public void WriteFile(DiskFile file)
        {
            CreateZipFile();
            try
            {
                file.CopyTo(_archive, true);
            }
            finally
            {
                file.Delete();
            }
        }

        public void WriteStream(Stream data, string filename)
        {
            CreateZipFile();
            var zfile = _archive.GetFile(filename);
            using (var zout = zfile.CreateWrite())
            {
                data.Seek(0, SeekOrigin.Begin);
                Utilities.CopyStream(data, zout);
            }
            data.Dispose();
        }
    }
}